﻿using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using System.ComponentModel;
using System.Reflection;

namespace EFCore7;

public class BloggingContext : DbContext
{
    //构造函数
    public BloggingContext()
    {
        //Database.EnsureDeleted();
        // 如果数据库表不存在则创建
        Database.EnsureCreated();
        // 执行自动迁移以将数据库与实体类定义同步
        Database.Migrate();
    }

    public DbSet<Biz_Blog> Blogs { get; set; }
    public DbSet<Biz_Post> Posts { get; set; }
    public DbSet<Biz_Coupons> Coupons { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            var type = entityType.ClrType;
            //通过DescriptionAttribute创建字段注释
            var descriptionAttrs = type.GetProperties().Where(c => c.IsDefined(typeof(DescriptionAttribute), true));
            foreach (var attr in descriptionAttrs)
            {
                var descriptionAttr = attr.GetCustomAttribute<DescriptionAttribute>();
                modelBuilder.Entity(type).Property(attr.Name).HasComment(descriptionAttr.Description);
            }
        }

        //modelBuilder.Entity<Biz_Blog>().HasData(new Biz_Blog { BlogId = 1, Url = @"https://devblogs.microsoft.com/dotnet", Rating = 5 },
        //          new Biz_Blog { BlogId = 2, Url = @"https://mytravelblog.com/", Rating = 4 });

        //modelBuilder.Entity<Biz_Post>().HasData(
        //        new Biz_Post
        //        { PostId = 1, BlogId = 1, Title = "What's new", Content = "Lorem ipsum dolor sit amet", Rating = 5 },
        //        new Biz_Post
        //        { PostId = 2, BlogId = 2, Title = "Around the World in Eighty Days", Content = "consectetur adipiscing elit", Rating = 5 },
        //        new Biz_Post
        //        { PostId = 3, BlogId = 2, Title = "Glamping *is* the way", Content = "sed do eiusmod tempor incididunt", Rating = 4 },
        //        new Biz_Post
        //        { PostId = 4, BlogId = 2, Title = "Travel in the time of pandemic", Content = "ut labore et dolore magna aliqua", Rating = 3 });

        //modelBuilder.Entity<Biz_Coupons>().HasData(new Biz_Coupons { Id = 1, Name = "tom", Owner = "jerry" },
        //          new Biz_Coupons { Id = 2, Name = "jerry", Owner = "jerry" });
        //modelBuilder.Entity<Biz_Blog>().HasKey(c => c.BlogId);
        //modelBuilder.Entity<Biz_Post>().HasKey(c => c.PostId);
        //modelBuilder.Entity<Biz_Post>().HasOne(c => c.Blog).WithMany(c => c.Posts).HasForeignKey(c => c.BlogId).OnDelete(DeleteBehavior.Cascade).IsRequired();

        base.OnModelCreating(modelBuilder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var _connectionString = "server=127.0.0.1;uid=root;pwd=123456;port=3306;database=ldh;Allow User Variables=True;sslMode=None";
        optionsBuilder.UseMySql(_connectionString, ServerVersion.Create(8, 0, 22, ServerType.MySql), builder =>
        {
            builder.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 });
        });
    }

    public async Task Seed()
    {
        var blogs = new List<Biz_Blog> {
            new Biz_Blog { BlogId = 1, Url = @"https://devblogs.microsoft.com/dotnet", Rating = 5 },
            new Biz_Blog { BlogId = 2, Url = @"https://mytravelblog.com/", Rating = 4 }
        };

        await AddRangeAsync(blogs);

        var posts = new List<Biz_Post> {
             new Biz_Post
                { PostId = 1, BlogId = 1, Title = "What's new", Content = "Lorem ipsum dolor sit amet", Rating = 5 },
                new Biz_Post
                { PostId = 2, BlogId = 2, Title = "Around the World in Eighty Days", Content = "consectetur adipiscing elit", Rating = 5 },
                new Biz_Post
                { PostId = 3, BlogId = 2, Title = "Glamping *is* the way", Content = "sed do eiusmod tempor incididunt", Rating = 4 },
                new Biz_Post
                { PostId = 4, BlogId = 2, Title = "Travel in the time of pandemic", Content = "ut labore et dolore magna aliqua", Rating = 3 }
        };

        await AddRangeAsync(posts);

        await SaveChangesAsync();
    }
}